package com.das.mechanic_base.adapter.task;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.bean.task.MapToDoList;
import com.das.mechanic_base.bean.task.SaveTodoBean;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.SwipeItemLayout;
import com.das.mechanic_base.utils.X3TimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：zhanglei on 2020-02-27 15:24
 * <p>
 * 邮箱：916256628@qq.com
 */
public class X3MyCrmTaskAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;

    private final int FINISH_TYPE = 1;

    private final int CUSTOM_TYPE = 0;

    /**
     * 未完成的待办事项
     */
    private List<SaveTodoBean> noList;

    /**
     * 已经完成的待办事项
     */
    private List<SaveTodoBean> finishList;

    /**
     * 已经完成的任务是否要展开
     */
    private boolean isShow;
    private final Drawable up;
    private final Drawable down;
    private final String today;

    public X3MyCrmTaskAdapter(Context mContext) {
        this.mContext = mContext;
        this.noList = new ArrayList<>();
        this.finishList = new ArrayList<>();

        up = ContextCompat.getDrawable(mContext,R.mipmap.x3_up);
        up.setBounds(0, 0, up.getMinimumWidth(), up.getMinimumHeight());

        down = ContextCompat.getDrawable(mContext,R.mipmap.x3_down);
        down.setBounds(0, 0, down.getMinimumWidth(), down.getMinimumHeight());

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//如果用到别的就用特定
        //字符表示，如星期F
        today = sdf.format(d);
    }

    /**
     * 刷新新数据
     * @param
     */
    public void changeTask(MapToDoList mapToDoList) {
        this.noList = mapToDoList.getUnDoList();
        this.finishList = mapToDoList.getCompleteList();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == 1) {
            return new MyFinishTaskHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_task_finish_item, parent, false));
        }
        return new MyTaskViewHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_task_visit_adapter, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        if (getItemViewType(position) == FINISH_TYPE) {
            MyFinishTaskHolder finishTaskHolder = (MyFinishTaskHolder) holder;

            String content = "";
            if (isShow) {
                content = mContext.getString(R.string.x3_task_hide);
                finishTaskHolder.tv_finish.setTextColor(Color.parseColor("#0077FF"));
                finishTaskHolder.v_show.setVisibility(View.VISIBLE);
                finishTaskHolder.tv_finish.setCompoundDrawables(null,null,up,null);
            }else {
                content = mContext.getString(R.string.x3_task_show);
                finishTaskHolder.tv_finish.setTextColor(Color.parseColor("#666666"));
                finishTaskHolder.v_show.setVisibility(View.INVISIBLE);
                finishTaskHolder.tv_finish.setCompoundDrawables(null,null,down,null);
            }

            finishTaskHolder.tv_finish.setText(content);

            finishTaskHolder.tv_finish.setOnClickListener(view -> {
                isShow = !isShow;
                notifyItemRangeChanged(position,getItemCount());
            });

        }else {

            MyTaskViewHolder taskViewHolder = (MyTaskViewHolder) holder;

            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) taskViewHolder.itemView.getLayoutParams();

            String content = "";
            String remindTime = "";
            String carOwnerUserName = "";
            String priorityLevel = "";
            List<String> carNumList;
            long id;
            int delIndex;
            if (position > noList.size()) {
                if (isShow) {
                    taskViewHolder.itemView.setVisibility(View.VISIBLE);
                    if (position == getItemCount() - 1) {
                        layoutParams.bottomMargin = X3ScreenUtils.dipToPx(20,mContext);
                    }else {
                        layoutParams.bottomMargin = 0;
                    }
                    layoutParams.height = RecyclerView.LayoutParams.WRAP_CONTENT;

                }else {
                    layoutParams.height = 0;
                    taskViewHolder.itemView.setVisibility(View.GONE);
                    layoutParams.bottomMargin = 0;
                }

                int index = position - noList.size() - 1;
                content = finishList.get(index).content + "";
                remindTime = finishList.get(index).remindTime;
                carOwnerUserName = finishList.get(index).carOwnerUserName;
                carNumList = finishList.get(index).carNumList;
                priorityLevel = finishList.get(index).priorityLevel + "";
                id = finishList.get(index).id;
                delIndex = index;

                taskViewHolder.iv_select.setImageResource(R.mipmap.x3_iv_task_status_select);

            }else {
                if (X3StringUtils.isListEmpty(finishList) && position == getItemCount() - 1) {
                    layoutParams.bottomMargin = X3ScreenUtils.dipToPx(20,mContext);
                }else {
                    layoutParams.bottomMargin = 0;
                }
                layoutParams.height = RecyclerView.LayoutParams.WRAP_CONTENT;
                taskViewHolder.itemView.setVisibility(View.VISIBLE);

                content = noList.get(position).content + "";
                remindTime = noList.get(position).remindTime;
                carOwnerUserName = noList.get(position).carOwnerUserName;
                carNumList = noList.get(position).carNumList;
                priorityLevel = noList.get(position).priorityLevel + "";
                id = noList.get(position).id;
                delIndex = position;

                taskViewHolder.iv_select.setImageResource(R.mipmap.x3_iv_task_status_unsele);
            }

            taskViewHolder.itemView.setLayoutParams(layoutParams);

            taskViewHolder.tv_title.setText(content);

            // 提醒时间
            if (X3StringUtils.isEmpty(remindTime)) {
                taskViewHolder.tv_notice.setVisibility(View.GONE);
                taskViewHolder.rl_main.setBackgroundColor(0);
            }else {
                taskViewHolder.tv_notice.setVisibility(View.VISIBLE);
                String taskTimeAfter = X3DateUtils.LongDateWithTime(remindTime);
                taskViewHolder.tv_notice.setText(mContext.getString(R.string.x3_notice_me) + "："+taskTimeAfter);

                boolean timeCompareSize = X3TimeUtils.getNewTimeCompareSize(today, remindTime);
                if (!timeCompareSize) {
                    taskViewHolder.tv_notice.setTextColor(Color.parseColor("#F64458"));
                    taskViewHolder.rl_main.setBackgroundColor(Color.parseColor("#40F64458"));
                }else {
                    taskViewHolder.rl_main.setBackgroundColor(0);
                    taskViewHolder.tv_notice.setTextColor(Color.parseColor("#666666"));
                }
            }

            // 客户姓名以及车牌号
            String carNum = "";
            if (!X3StringUtils.isListEmpty(carNumList)) {
                for (int i = 0; i < carNumList.size(); i++) {
                    if (i == 0) {
                        carNum = carNumList.get(i);
                    } else {
                        carNum = carNum + ", " + carNumList.get(i);
                    }
                }
            }

            carNum = X3StringUtils.isEmpty(carNum) ? "" : "（" + carNum + "）";
            carOwnerUserName = X3StringUtils.isEmpty(carOwnerUserName) ? "" : carOwnerUserName;
            taskViewHolder.tv_user.setText(mContext.getString(R.string.x3_user_title) + "：" + carOwnerUserName + carNum);
            if (X3StringUtils.isEmpty(carOwnerUserName) && X3StringUtils.isEmpty(carNum)) {
                taskViewHolder.tv_user.setVisibility(View.GONE);
            }else {
                taskViewHolder.tv_user.setVisibility(View.VISIBLE);
            }

            if ("LEVEL_MI".equals(priorityLevel)) {
                taskViewHolder.tv_notify.setVisibility(View.VISIBLE);
                taskViewHolder.tv_notify.setText(Html.fromHtml(mContext.getString(R.string.x3_priority) + "：<font color='#FFC602'>" + mContext.getString(R.string.x3_urgency) + "</font>"));
            }else if("LEVEL_HI".equals(priorityLevel)) {
                taskViewHolder.tv_notify.setVisibility(View.VISIBLE);
                taskViewHolder.tv_notify.setText(Html.fromHtml(mContext.getString(R.string.x3_priority) + "：<font color='#F64458'>" + mContext.getString(R.string.x3_more_urgency) + "</font>"));
            }else {
                taskViewHolder.tv_notify.setVisibility(View.GONE);
            }

            if (position < noList.size()) {
                /**
                 * 完成代办事项
                 */
                taskViewHolder.iv_select.setOnClickListener(view -> {
                    taskViewHolder.iv_select.setImageResource(R.mipmap.x3_iv_task_status_select);
                    if (iOnTaskChange != null) {
                        iOnTaskChange.iOnTaskComplete(id);
                    }
                });
            }else {
                taskViewHolder.iv_select.setOnClickListener(view -> {
                    taskViewHolder.iv_select.setImageResource(R.mipmap.x3_iv_task_status_unsele);
                    if (iOnTaskChange != null) {
                        iOnTaskChange.iOnCancelComplete(id);
                    }
                });
            }

            taskViewHolder.tv_right.setOnClickListener(v -> {
                // 删除
                if (iOnTaskChange != null) {
                    iOnTaskChange.iOnTaskDelete(id);
                }
                if (position < noList.size()) {
                    noList.remove(position);//删除数据源,移除集合中当前下标的数据
                }else {
                    finishList.remove(delIndex);
                }

                notifyItemRemoved(position);//刷新被删除的地方
                notifyDataSetChanged();
            });

            taskViewHolder.rl_main.setOnClickListener(view -> {
                if (iOnTaskChange != null) {
                    iOnTaskChange.iOnTaskCheck(id);
                }
            });
        }
    }

    @Override
    public int getItemViewType(int position) {

        if (position == noList.size()) {
            return FINISH_TYPE;
        }
        return CUSTOM_TYPE;
    }

    @Override
    public int getItemCount() {
        return (finishList == null || finishList.size() == 0) ? noList.size() : noList.size() + finishList.size() + 1;
    }

    IOnTaskChange iOnTaskChange;

    public void setiOnTaskChange(IOnTaskChange iOnTaskChange) {
        this.iOnTaskChange = iOnTaskChange;
    }

    public interface IOnTaskChange {
        /**
         * 删除待办事项
         * @param id
         */
        void iOnTaskDelete(long id);

        /**
         * 完成待办事项
         * @param id
         */
        void iOnTaskComplete(long id);

        /**
         * 取消待办事项
         * @param id
         */
        void iOnCancelComplete(long id);

        /**
         * 跳转查看完整待办事项
         * @param id
         */
        void iOnTaskCheck(long id);
    }

    class MyTaskViewHolder extends RecyclerView.ViewHolder {
        TextView tv_title;
        TextView tv_user;
        TextView tv_notice;
        TextView tv_notify;
        View v_line;
        ImageView iv_select;
        TextView tv_right;
        RelativeLayout rl_main;
        SwipeItemLayout sl_view;
        public MyTaskViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_title = itemView.findViewById(R.id.tv_title);
            tv_user = itemView.findViewById(R.id.tv_user);
            tv_notice = itemView.findViewById(R.id.tv_notice);
            tv_notify = itemView.findViewById(R.id.tv_notify);
            v_line = itemView.findViewById(R.id.v_line);
            iv_select = itemView.findViewById(R.id.iv_select);
            tv_right = itemView.findViewById(R.id.tv_right);
            rl_main = itemView.findViewById(R.id.rl_main);
            sl_view = itemView.findViewById(R.id.sl_view);
        }
    }

    class MyFinishTaskHolder extends RecyclerView.ViewHolder{
        TextView tv_finish;
        View v_show;
        public MyFinishTaskHolder(@NonNull View itemView) {
            super(itemView);
            tv_finish = itemView.findViewById(R.id.tv_finish);
            v_show = itemView.findViewById(R.id.v_show);
        }
    }
}
